package com.lianzai.mobile.controller;

import com.alibaba.fastjson.JSON;
import com.lianzai.car.domain.CarParkInfoDO;
import com.lianzai.car.service.CarLogService;
import com.lianzai.common.annotation.NoLoginAuthRequired;
import com.lianzai.common.constant.Constant;
import com.lianzai.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;

@Slf4j
@Controller
public class MobileLoginController {
    @Autowired
    private CarLogService carLogService;


    @RequestMapping("/mobile/login")
    public ModelAndView mobileIndex(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("mobile/login");
    }

    @NoLoginAuthRequired
    @RequestMapping("/mobile/provisionalCarSuccess")
    public ModelAndView provisionalCarSuccess(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("wechat/provisionalCarSuccess");
    }

    @NoLoginAuthRequired
    @RequestMapping("/mobile/provisionalCar/{exitId}")
    public ModelAndView provisionalCar(@PathVariable("exitId") String exitId, Model model, HttpServletRequest request){
        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute(Constant.CURR_OPEN_ID); //当前用户OPENID

        CarParkInfoDO parkInfo = carLogService.getParkInfoByCameraId(Long.valueOf(exitId));
        log.info("根据相机ID查询相机支付信息：{}", parkInfo);
        if(parkInfo == null){
            return new ModelAndView("wechat/provisionalCarFail");
        }else {
            log.info("查询相机信息：{}", JSON.toJSONString(parkInfo));
            model.addAttribute("exitId", exitId);
            model.addAttribute("openid", openid);
            model.addAttribute("carNo", parkInfo.getCarNumber());
            model.addAttribute("communityInfo", parkInfo.getCommunityName());
            model.addAttribute("startTime", DateUtils.format(parkInfo.getStartTime(), DateUtils.DATE_TIME_PATTERN1));
            model.addAttribute("entTime", DateUtils.format(parkInfo.getEndTime(), DateUtils.DATE_TIME_PATTERN1));
            model.addAttribute("times", BigDecimal.valueOf(parkInfo.getDuration()/3600.0).setScale(2, BigDecimal.ROUND_HALF_DOWN));
            model.addAttribute("totalFee", BigDecimal.valueOf(parkInfo.getFee()).setScale(2, BigDecimal.ROUND_HALF_DOWN));
            return new ModelAndView("wechat/provisionalCar");
        }
    }
}